import { useState, useCallback, useEffect } from 'react';
import {
  ParsedChat,
  GeneratedReply,
  EmojiRecommendation,
  DetectedTask,
  TaskPlan,
  ReplyGoal,
  ReplyStyle,
} from './types';
import {
  GlassCard,
  GlassButton,
  GlassInput,
  ChatInput,
  GoalSelector,
  ScreenshotUpload,
  ReplyList,
  EmojiGrid,
  TaskPlanDisplay,
} from './components';
import {
  chatParser,
  replyGenerator,
  emojiRecommender,
  taskDetector,
  planGenerator,
  screenshotParser,
  defaultApiService,
  emojiGenerator,
  type GeneratedEmoji,
} from './services';

/**
 * 存储键名
 */
const API_KEY_STORAGE_KEY = 'smart_chat_reply_api_key';
const API_URL_STORAGE_KEY = 'smart_chat_reply_api_url';

/**
 * 默认 API 地址 (GitCode API v5)
 */
const DEFAULT_API_URL = 'https://api.gitcode.com/api/v5/chat/completions';

/**
 * 默认 API 密钥（路演演示用）
 */
const DEFAULT_API_KEY = 'xy63rLezCgJmcA_ibeHoz5_1';

/**
 * Smart Chat Reply 主应用组件
 * 实现毛玻璃风格的响应式布局
 * Requirements: 8.4, 8.5
 */
function App() {
  // 输入状态
  const [chatInput, setChatInput] = useState('');
  const [selectedGoal, setSelectedGoal] = useState<ReplyGoal | null>(null);
  const [customGoalText, setCustomGoalText] = useState('');
  const [selectedStyle, setSelectedStyle] = useState<ReplyStyle>('casual');

  // 初始化时从 localStorage 读取 API 配置，如果没有则使用默认密钥
  useEffect(() => {
    const savedApiKey = localStorage.getItem(API_KEY_STORAGE_KEY);
    const savedApiUrl = localStorage.getItem(API_URL_STORAGE_KEY);
    
    // 使用保存的密钥或默认密钥
    const keyToUse = savedApiKey || DEFAULT_API_KEY;
    const urlToUse = savedApiUrl || DEFAULT_API_URL;
    
    defaultApiService.updateConfig({ 
      apiKey: keyToUse,
      apiUrl: urlToUse
    });
  }, []);

  // 解析和生成结果状态
  const [parsedChat, setParsedChat] = useState<ParsedChat | null>(null);
  const [generatedReplies, setGeneratedReplies] = useState<GeneratedReply[]>([]);
  const [recommendedEmojis, setRecommendedEmojis] = useState<EmojiRecommendation | null>(null);
  const [detectedTasks, setDetectedTasks] = useState<DetectedTask[]>([]);
  const [generatedPlans, setGeneratedPlans] = useState<TaskPlan[]>([]);

  // AI 表情包生成状态
  const [emojiPrompt, setEmojiPrompt] = useState('');
  const [generatedEmojiList, setGeneratedEmojiList] = useState<GeneratedEmoji[]>([]);
  const [isGeneratingEmoji, setIsGeneratingEmoji] = useState(false);
  const [emojiError, setEmojiError] = useState<string | null>(null);

  // 加载和错误状态
  const [isLoading, setIsLoading] = useState(false);
  const [isScreenshotProcessing, setIsScreenshotProcessing] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [screenshotError, setScreenshotError] = useState<string | null>(null);

  // 处理聊天记录分析
  const handleAnalyze = useCallback(async () => {
    if (!chatInput.trim()) {
      setError('请输入聊天记录');
      return;
    }

    setIsLoading(true);
    setError(null);

    try {
      // 1. 解析聊天记录
      const parseResult = chatParser.parse(chatInput);
      if (!parseResult.success || !parseResult.data) {
        setError(parseResult.error || '解析聊天记录失败');
        setIsLoading(false);
        return;
      }

      const parsed = parseResult.data;
      setParsedChat(parsed);

      // 2. 生成回复建议
      let replies: GeneratedReply[];
      if (selectedGoal === 'custom' && customGoalText.trim()) {
        // 使用自定义目标生成回复
        replies = await replyGenerator.generateFromGoal(customGoalText, {
          goal: 'custom',
          style: selectedStyle,
        });
      } else {
        // 基于聊天上下文生成回复
        replies = await replyGenerator.generate(parsed, {
          goal: selectedGoal || undefined,
          style: selectedStyle,
        });
      }
      setGeneratedReplies(replies);

      // 3. 推荐表情包
      const emojis = emojiRecommender.recommend(parsed.emotionalTone);
      setRecommendedEmojis(emojis);

      // 4. 检测任务
      const tasks = await taskDetector.detect(parsed);
      setDetectedTasks(tasks);

      // 5. 为检测到的任务生成计划
      const plans: TaskPlan[] = [];
      for (const task of tasks) {
        const plan = await planGenerator.generate(task);
        plans.push(plan);
      }
      setGeneratedPlans(plans);

    } catch (err) {
      console.error('分析失败:', err);
      setError(err instanceof Error ? err.message : '分析过程中发生错误');
    } finally {
      setIsLoading(false);
    }
  }, [chatInput, selectedGoal, customGoalText, selectedStyle]);

  // 处理截图上传
  const handleScreenshotUpload = useCallback(async (file: File) => {
    setIsScreenshotProcessing(true);
    setScreenshotError(null);

    try {
      const result = await screenshotParser.parse(file);
      
      if (!result.success) {
        setScreenshotError(result.error || '截图识别失败');
        return;
      }

      if (result.needsConfirmation) {
        setScreenshotError(`识别置信度较低 (${Math.round(result.confidence * 100)}%)，请检查识别结果`);
      }

      // 将识别结果填入输入框
      setChatInput(result.rawText);
      
      if (result.parsedChat) {
        setParsedChat(result.parsedChat);
      }
    } catch (err) {
      console.error('截图处理失败:', err);
      setScreenshotError(err instanceof Error ? err.message : '截图处理失败');
    } finally {
      setIsScreenshotProcessing(false);
    }
  }, []);

  // 处理复制回调
  const handleCopy = useCallback((content: string) => {
    console.log('已复制:', content.substring(0, 50) + '...');
  }, []);

  // 生成 AI 表情包
  const handleGenerateEmoji = useCallback(async () => {
    if (!emojiPrompt.trim()) {
      setEmojiError('请输入表情包描述');
      return;
    }

    setIsGeneratingEmoji(true);
    setEmojiError(null);

    try {
      const result = await emojiGenerator.generate(emojiPrompt);
      setGeneratedEmojiList(prev => [result, ...prev].slice(0, 6)); // 最多保留6个
      setEmojiPrompt(''); // 清空输入
    } catch (err) {
      console.error('表情包生成失败:', err);
      setEmojiError(err instanceof Error ? err.message : '表情包生成失败');
    } finally {
      setIsGeneratingEmoji(false);
    }
  }, [emojiPrompt]);

  // 清空所有状态
  const handleClear = useCallback(() => {
    setChatInput('');
    setSelectedGoal(null);
    setCustomGoalText('');
    setParsedChat(null);
    setGeneratedReplies([]);
    setRecommendedEmojis(null);
    setDetectedTasks([]);
    setGeneratedPlans([]);
    setError(null);
    setScreenshotError(null);
    setGeneratedEmojiList([]);
    setEmojiError(null);
  }, []);

  return (
    <div className="min-h-screen p-4 md:p-6 lg:p-8">
      {/* 页面标题 */}
      <header className="text-center mb-6 md:mb-8 animate-fade-in">
        <h1 className="text-3xl md:text-4xl font-bold text-emerald-600 mb-2">
          ✨ Smart Chat Reply
        </h1>
        <p className="text-gray-600 text-sm md:text-base">
          智能聊天回复工具 · 高情商回复 · 表情包推荐 · 任务识别
        </p>
        
        {/* API 配置已隐藏 - 使用默认配置 */}
      </header>

      {/* 主内容区域 - 响应式布局 */}
      <div className="max-w-7xl mx-auto">
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          
          {/* 左侧：输入区域 */}
          <div className="space-y-4 animate-slide-up">
            <GlassCard>
              <h2 className="text-lg font-semibold text-emerald-600 mb-4 flex items-center gap-2">
                <span>💬</span> 输入聊天记录
              </h2>
              
              {/* 聊天记录输入 */}
              <ChatInput
                value={chatInput}
                onChange={setChatInput}
                disabled={isLoading}
                error={error || undefined}
              />

              {/* 截图上传 */}
              <div className="mt-4">
                <ScreenshotUpload
                  onFileSelect={handleScreenshotUpload}
                  isProcessing={isScreenshotProcessing}
                  error={screenshotError || undefined}
                />
              </div>

              {/* 目标选择器 */}
              <div className="mt-4">
                <GoalSelector
                  selectedGoal={selectedGoal}
                  onGoalChange={setSelectedGoal}
                  customGoalText={customGoalText}
                  onCustomGoalTextChange={setCustomGoalText}
                  disabled={isLoading}
                />
              </div>

              {/* 风格选择 */}
              <div className="mt-4">
                <label className="block text-emerald-700 text-sm font-medium mb-2">
                  回复风格
                </label>
                <div className="flex gap-2">
                  <GlassButton
                    variant={selectedStyle === 'casual' ? 'primary' : 'default'}
                    size="sm"
                    onClick={() => setSelectedStyle('casual')}
                    disabled={isLoading}
                  >
                    😊 轻松
                  </GlassButton>
                  <GlassButton
                    variant={selectedStyle === 'formal' ? 'primary' : 'default'}
                    size="sm"
                    onClick={() => setSelectedStyle('formal')}
                    disabled={isLoading}
                  >
                    📝 正式
                  </GlassButton>
                </div>
              </div>

              {/* 操作按钮 */}
              <div className="mt-6 flex gap-3">
                <GlassButton
                  variant="primary"
                  size="lg"
                  onClick={handleAnalyze}
                  loading={isLoading}
                  disabled={!chatInput.trim()}
                  className="flex-1"
                >
                  {isLoading ? '分析中...' : '🚀 开始分析'}
                </GlassButton>
                <GlassButton
                  variant="default"
                  size="lg"
                  onClick={handleClear}
                  disabled={isLoading}
                >
                  🗑️ 清空
                </GlassButton>
              </div>
            </GlassCard>

            {/* 解析结果预览 */}
            {parsedChat && (
              <GlassCard className="animate-fade-in">
                <h3 className="text-sm font-medium text-emerald-700 mb-2 flex items-center gap-2">
                  <span>📊</span> 解析结果
                </h3>
                <div className="text-sm text-gray-600 space-y-1">
                  <p>参与者: {parsedChat.participants.join(', ')}</p>
                  <p>消息数: {parsedChat.messages.length}</p>
                  <p>情感基调: {getToneLabel(parsedChat.emotionalTone)}</p>
                </div>
              </GlassCard>
            )}
          </div>

          {/* 右侧：结果展示区域 */}
          <div className="space-y-4 animate-slide-up" style={{ animationDelay: '0.1s' }}>
            {/* 回复建议 */}
            <GlassCard>
              <h2 className="text-lg font-semibold text-emerald-600 mb-4 flex items-center gap-2">
                <span>💡</span> 回复建议
              </h2>
              <ReplyList
                replies={generatedReplies}
                isLoading={isLoading}
                onCopy={handleCopy}
                onEmojiGenerated={(emoji) => {
                  setGeneratedEmojiList(prev => [emoji, ...prev].slice(0, 6));
                }}
              />
            </GlassCard>

            {/* 表情包推荐 */}
            <GlassCard>
              <EmojiGrid
                recommendation={recommendedEmojis}
                isLoading={isLoading}
              />
            </GlassCard>

            {/* AI 表情包生成 */}
            <GlassCard>
              <h2 className="text-lg font-semibold text-orange-500 mb-4 flex items-center gap-2">
                <span>🎨</span> AI 生成表情包
              </h2>
              <div className="space-y-3">
                <GlassInput
                  value={emojiPrompt}
                  onChange={setEmojiPrompt}
                  placeholder="描述你想要的表情包，如：一只震惊的柴犬，眼睛瞪大"
                  disabled={isGeneratingEmoji}
                />
                <GlassButton
                  variant="primary"
                  size="md"
                  onClick={handleGenerateEmoji}
                  loading={isGeneratingEmoji}
                  disabled={!emojiPrompt.trim()}
                  className="w-full"
                >
                  {isGeneratingEmoji ? '生成中...' : '✨ 生成表情包'}
                </GlassButton>
                {emojiError && (
                  <p className="text-red-500 text-sm">{emojiError}</p>
                )}
                
                {/* 生成的表情包展示 */}
                {generatedEmojiList.length > 0 && (
                  <div className="grid grid-cols-3 gap-2 mt-4">
                    {generatedEmojiList.map((emoji) => (
                      <div
                        key={emoji.id}
                        className="relative aspect-square bg-gray-100 rounded-lg overflow-hidden cursor-pointer hover:ring-2 hover:ring-emerald-400/50 transition-all"
                        onClick={async () => {
                          try {
                            await navigator.clipboard.writeText(emoji.url);
                            handleCopy(emoji.url);
                          } catch (e) {
                            console.error('复制失败', e);
                          }
                        }}
                      >
                        <img
                          src={emoji.url}
                          alt={emoji.prompt}
                          className="w-full h-full object-cover"
                        />
                        <div className="absolute inset-0 bg-black/50 opacity-0 hover:opacity-100 transition-opacity flex items-center justify-center">
                          <span className="text-white text-xs">点击复制</span>
                        </div>
                      </div>
                    ))}
                  </div>
                )}
                
                {/* 提示词建议 */}
                <div className="mt-3">
                  <p className="text-gray-500 text-xs mb-2">💡 试试这些提示词：</p>
                  <div className="flex flex-wrap gap-1">
                    {['震惊柴犬', '比心小猫', '打工人', '摸鱼中', '求原谅'].map((tip) => (
                      <button
                        key={tip}
                        onClick={() => setEmojiPrompt(tip)}
                        className="px-2 py-1 bg-orange-100 rounded text-xs text-orange-600 hover:bg-orange-200 transition-colors"
                      >
                        {tip}
                      </button>
                    ))}
                  </div>
                </div>
              </div>
            </GlassCard>

            {/* 任务计划 */}
            <GlassCard>
              <h2 className="text-lg font-semibold text-emerald-600 mb-4 flex items-center gap-2">
                <span>📋</span> 任务识别
              </h2>
              <TaskPlanDisplay
                tasks={detectedTasks}
                plans={generatedPlans}
                isLoading={isLoading}
                onCopy={handleCopy}
              />
            </GlassCard>
          </div>
        </div>
      </div>

      {/* 页脚 */}
      <footer className="text-center mt-8 text-gray-400 text-sm animate-fade-in">
        <p>Smart Chat Reply © 2024 · 让沟通更智能</p>
      </footer>
    </div>
  );
}

/**
 * 获取情感基调的中文标签
 */
function getToneLabel(tone: string): string {
  const labels: Record<string, string> = {
    happy: '😊 开心',
    sad: '😢 悲伤',
    comfort: '🤗 安慰',
    funny: '😄 幽默',
    grateful: '🙏 感激',
    apologetic: '😔 道歉',
    neutral: '😐 中性',
  };
  return labels[tone] || tone;
}

export default App;
